<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🤖 A2A多智能体协商系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        .container {
            width: 95%;
            max-width: 1400px;
            height: 95vh;
            display: flex;
            gap: 15px;
        }

        .left-panel {
            flex: 1;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .right-panel {
            flex: 1;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .panel-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .panel-header h2 {
            font-size: 20px;
            margin-bottom: 5px;
        }

        .panel-header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .input-section {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
        }

        .input-group {
            margin-bottom: 15px;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }

        .input-field {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }

        .input-field:focus {
            border-color: #4facfe;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
        }

        .submit-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .negotiation-panel {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #fafafa;
        }

        .negotiation-step {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #4facfe;
            animation: slideIn 0.5s ease-out;
        }

        .negotiation-step.thinking {
            border-left-color: #ff9800;
            background: linear-gradient(135deg, #fff3e0 0%, #ffffff 100%);
        }

        .negotiation-step.conflict {
            border-left-color: #f44336;
            background: linear-gradient(135deg, #ffebee 0%, #ffffff 100%);
        }

        .negotiation-step.agreement {
            border-left-color: #4caf50;
            background: linear-gradient(135deg, #e8f5e8 0%, #ffffff 100%);
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .step-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .step-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-size: 16px;
        }

        .step-title {
            font-weight: 600;
            color: #333;
            flex: 1;
        }

        .step-time {
            font-size: 12px;
            color: #666;
        }

        .step-content {
            color: #555;
            line-height: 1.6;
        }

        .agent-dialogue {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
            border-left: 3px solid #4facfe;
        }

        .agent-name {
            font-weight: 600;
            color: #1976d2;
            margin-bottom: 5px;
        }

        .agent-message {
            color: #333;
        }

        .decision-options {
            margin: 15px 0;
        }

        .option {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 8px;
            padding: 10px 15px;
            margin: 5px 0;
            cursor: pointer;
            transition: all 0.3s;
        }

        .option:hover {
            background: #bbdefb;
            border-color: #1976d2;
        }

        .option.selected {
            background: #1976d2;
            color: white;
            border-color: #0d47a1;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            margin: 20px 0;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4facfe, #00f2fe);
            width: 0%;
            transition: width 0.5s ease;
        }

        .status-panel {
            padding: 20px;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .status-label {
            font-weight: 500;
        }

        .status-value {
            font-weight: 600;
            color: #4facfe;
        }

        .agent-status {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-left: 10px;
        }

        .agent-status.online {
            background: #4caf50;
        }

        .agent-status.offline {
            background: #f44336;
        }

        .thinking-animation {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #ff9800;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .data-flow-panel {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #fafafa;
        }

        .data-flow-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
            text-align: center;
        }

        .agent-flow {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #2196f3;
        }

        .agent-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .agent-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            font-size: 18px;
        }

        .agent-info h3 {
            margin: 0;
            font-size: 16px;
            color: #333;
        }

        .agent-info p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }

        .data-section {
            margin-bottom: 15px;
        }

        .data-section h4 {
            margin: 0 0 10px 0;
            color: #555;
            font-size: 14px;
            font-weight: 600;
        }

        .data-content {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #333;
            max-height: 150px;
            overflow-y: auto;
        }

        .flow-arrow {
            text-align: center;
            margin: 10px 0;
            color: #666;
            font-size: 20px;
        }

        .negotiation-flow {
            background: linear-gradient(135deg, #fff3e0 0%, #ffffff 100%);
            border-left-color: #ff9800;
        }

        .error-flow {
            background: linear-gradient(135deg, #ffebee 0%, #ffffff 100%);
            border-left-color: #f44336;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                height: auto;
                min-height: 100vh;
            }

            .left-panel, .right-panel {
                flex: none;
                height: auto;
                min-height: 50vh;
            }

            .data-flow-panel {
                max-height: 60vh;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧面板：输入和控制 -->
        <div class="left-panel">
            <div class="panel-header">
                <h2>🎯 旅行需求输入</h2>
                <p>告诉我们您的旅行计划，我们的AI团队将为您协商最优方案</p>
            </div>

            <div class="input-section">
                <div class="input-group">
                    <label for="destination">📍 目的地</label>
                    <input type="text" id="destination" class="input-field" placeholder="例如：汉堡、北京、东京">
                </div>

                <div class="input-group">
                    <label for="duration">⏰ 旅行天数</label>
                    <input type="text" id="duration" class="input-field" placeholder="例如：3天、1周">
                </div>

                <div class="input-group">
                    <label for="budget">💰 预算范围</label>
                    <input type="text" id="budget" class="input-field" placeholder="例如：800欧元、5000元">
                </div>

                <div class="input-group">
                    <label for="preferences">🎨 偏好和要求</label>
                    <input type="text" id="preferences" class="input-field" placeholder="例如：户外摄影、历史景点、美食">
                </div>

                <div class="input-group">
                    <label for="constraints">⚠️ 特殊限制</label>
                    <input type="text" id="constraints" class="input-field" placeholder="例如：对天气敏感、不喜欢人群">
                </div>

                <button class="submit-btn" id="submitBtn" onclick="startNegotiation()">
                    🚀 开始AI团队协商
                </button>
            </div>

            <div class="status-panel">
                <div class="status-item">
                    <span class="status-label">🌤️ WeatherAgent</span>
                    <span class="agent-status online" id="weatherStatus"></span>
                </div>
                <div class="status-item">
                    <span class="status-label">💰 BudgetAgent</span>
                    <span class="agent-status offline" id="budgetStatus"></span>
                </div>
                <div class="status-item">
                    <span class="status-label">🗺️ TravelAgent</span>
                    <span class="agent-status offline" id="travelStatus"></span>
                </div>
                <div class="status-item">
                    <span class="status-label">🍽️ RestaurantAgent</span>
                    <span class="agent-status offline" id="restaurantStatus"></span>
                </div>
                <div class="status-item">
                    <span class="status-label">🎯 Coordinator</span>
                    <span class="agent-status offline" id="coordinatorStatus"></span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <div class="status-item">
                    <span class="status-label">协商进度</span>
                    <span class="status-value" id="progressText">0%</span>
                </div>
            </div>
        </div>

        <!-- 右侧面板：协商过程展示 -->
        <div class="right-panel">
            <div class="panel-header">
                <h2>🧠 AI团队协商过程</h2>
                <p>实时查看智能体间的思考、讨论和决策过程</p>
            </div>

            <div class="negotiation-panel" id="negotiationPanel">
                <div class="welcome-screen">
                    <h3>🌟 欢迎使用A2A多智能体协商系统！</h3>
                    <p>我们的AI团队将通过以下步骤为您服务：</p>
                    <ul class="feature-list">
                        <li>🔍 <strong>需求分析</strong> - 理解您的旅行需求</li>
                        <li>🌤️ <strong>天气评估</strong> - 分析天气对活动的影响</li>
                        <li>💰 <strong>预算分析</strong> - 评估成本和资源分配</li>
                        <li>🤝 <strong>智能协商</strong> - Agent间讨论最优方案</li>
                        <li>✅ <strong>方案优化</strong> - 生成个性化推荐</li>
                    </ul>
                    <p style="margin-top: 20px; color: #666;">请在左侧输入您的旅行需求，然后点击"开始协商"按钮。</p>
                </div>
            </div>
        </div>

        <!-- 新增：数据流展示面板 -->
        <div class="right-panel">
            <div class="panel-header">
                <h2>🔄 Agent协作数据流</h2>
                <p>实时查看Agent间的输入输出和数据传递</p>
            </div>

            <div class="data-flow-panel" id="dataFlowPanel">
                <div class="data-flow-title">等待协商开始...</div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let websocket = null;
        let isConnected = false;
        let negotiationSteps = [];
        let currentStep = 0;
    let activeTimers = []; // 保存模拟/延迟步骤的定时器ID
    let negotiationId = 0; // 当前协商会话ID
    let negotiationEnded = false; // 标记当前协商是否已结束

        // DOM元素
        const negotiationPanel = document.getElementById('negotiationPanel');
        const dataFlowPanel = document.getElementById('dataFlowPanel');
        const submitBtn = document.getElementById('submitBtn');
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            connectWebSocket();
            checkAgentsStatus();
            setInterval(checkAgentsStatus, 10000); // 每10秒检查一次
        });

        // 连接WebSocket
        function connectWebSocket() {
            try {
                websocket = new WebSocket('ws://localhost:8000/ws');

                websocket.onopen = function(event) {
                    console.log('WebSocket连接已建立');
                    isConnected = true;
                };

                websocket.onmessage = function(event) {
                    const data = JSON.parse(event.data);
                    handleWebSocketMessage(data);
                };

                websocket.onclose = function(event) {
                    console.log('WebSocket连接已关闭');
                    isConnected = false;
                };

                websocket.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    isConnected = false;
                };

            } catch (error) {
                console.error('无法连接WebSocket:', error);
                isConnected = false;
            }
        }

        // 处理WebSocket消息
        function handleWebSocketMessage(data) {
            // 兼容后端发送格式：{type: 'thinking', step: {...}} 或 {type:'negotiation_step', step:{...}}
            const step = data.step || data; // 若直接就是step

            // 如果收到旧会话（带sessionId且不匹配当前）数据，直接忽略
            if (step && step.sessionId !== undefined && step.sessionId !== negotiationId) {
                return;
            }
            // 协商已结束时忽略新的 thinking/dialogue/decision 类型的延迟残留
            if (negotiationEnded && ['thinking','dialogue','decision','conflict'].includes(data.type)) {
                return;
            }

            switch(data.type) {
                case 'plan_created': {
                    addNegotiationStep({
                        type: 'thinking',
                        title: '🧠 计划已生成',
                        content: `检测到${(step.steps||[]).length}个执行步骤：` + (step.steps||[]).map(s=>s.agent).join(' → ')
                    });
                    incrementProgress();
                    break;
                }
                case 'step_start': {
                    addNegotiationStep({
                        type: 'thinking',
                        title: `🔄 第${step.step_index}/${step.total_steps}步：调用 ${step.agent}`,
                        content: '输入: ' + formatData(step.input)
                    });
                    incrementProgress();
                    break;
                }
                case 'step_result': {
                    addNegotiationStep({
                        type: 'dialogue',
                        title: `✅ ${step.agent} 返回结果`,
                        content: '输出: ' + formatData(step.result)
                    });
                    updateProgress(step.progress || internalProgress);
                    break;
                }
                case 'finalizing': {
                    addNegotiationStep({
                        type: 'thinking',
                        title: '🧩 正在整合结果',
                        content: step.message || '汇总各Agent结果中...'
                    });
                    incrementProgress();
                    break;
                }
                case 'final_result': {
                    showFinalResult(step.final_response || step.result || '处理完成');
                    updateProgress(100);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '🚀 开始AI团队协商';
                    negotiationEnded = true;
                    clearAllTimers();
                    break;
                }
                case 'negotiation_step': {
                    addNegotiationStep(step);
                    break;
                }
                case 'thinking': {
                    const agent = step.agent || 'Agent';
                    const msg = step.content || step.message || '';
                    showThinking(agent, msg);
                    incrementProgress();
                    break;
                }
                case 'dialogue': {
                    const agent = step.agent || 'Agent';
                    const msg = step.message || step.content || '';
                    addAgentDialogue(agent, msg);
                    incrementProgress();
                    break;
                }
                case 'conflict': {
                    addNegotiationStep({
                        type: 'conflict',
                        title: step.title || '⚠️ 冲突检测',
                        content: step.content || step.message || ''
                    });
                    incrementProgress();
                    break;
                }
                case 'decision': {
                    addNegotiationStep({
                        type: 'decision',
                        title: step.title || '🤝 协商方案',
                        content: step.content || ''
                    });
                    if (step.options) {
                        showDecisionOptions(step.options);
                    }
                    incrementProgress();
                    break;
                }
                case 'agreement': {
                    addNegotiationStep({
                        type: 'agreement',
                        title: step.title || '✅ 协商达成',
                        content: step.content || step.message || ''
                    });
                    updateProgress(100);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '🚀 开始AI团队协商';
                    negotiationEnded = true;
                    clearAllTimers();
                    break;
                }
                case 'progress': {
                    if (typeof data.progress === 'number') updateProgress(data.progress);
                    break;
                }
                case 'final_result': {
                    showFinalResult(step.result || data.result);
                    updateProgress(100);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '🚀 开始AI团队协商';
                    negotiationEnded = true;
                    clearAllTimers();
                    break;
                }
                case 'data_flow': {
                    addDataFlowEntry(data);
                    break;
                }
                default: {
                    // 未知类型按普通步骤展示
                    if (step.title || step.content) {
                        addNegotiationStep(step);
                        incrementProgress();
                    }
                }
            }
        }

        // 开始协商
        function startNegotiation() {
            const destination = document.getElementById('destination').value.trim();
            const duration = document.getElementById('duration').value.trim();
            const budget = document.getElementById('budget').value.trim();
            const preferences = document.getElementById('preferences').value.trim();
            const constraints = document.getElementById('constraints').value.trim();

            if (!destination || !duration || !budget) {
                alert('请至少填写目的地、旅行天数和预算！');
                return;
            }

            // 构建用户需求消息
            const userMessage = `我想去${destination}旅行${duration}，预算${budget}。我喜欢${preferences || '各种活动'}。${constraints ? '特殊要求：' + constraints : ''}`;

            // 清空协商面板
            negotiationPanel.innerHTML = '';
            dataFlowPanel.innerHTML = '<div class="data-flow-title">数据流追踪中...</div>';

            // 重置进度
            currentStep = 0;
            updateProgress(0);
            negotiationId += 1; // 新会话ID
            negotiationEnded = false;
            clearAllTimers();

            // 禁用提交按钮
            submitBtn.disabled = true;
            submitBtn.textContent = '🤖 AI团队协商中...';
            
            // 显示处理状态
            addNegotiationStep({
                type: 'thinking',
                title: '🚀 系统启动中',
                content: '正在连接AI智能体团队，请稍候...'
            });
            
            // 为复杂请求添加进度提示
            let progressSteps = [
                { delay: 10000, title: '🧠 CoordinatorAgent分析中', content: '正在分析您的旅行需求...' },
                { delay: 30000, title: '🌤️ WeatherAgent查询中', content: '正在获取天气信息...' },
                { delay: 50000, title: '💰 BudgetAgent计算中', content: '正在进行预算分析...' },
                { delay: 70000, title: '🗺️ TravelAgent规划中', content: '正在制定旅行方案...' },
                { delay: 90000, title: '🍽️ RestaurantAgent推荐中', content: '正在搜索美食推荐...' },
                { delay: 120000, title: '🤝 智能体协商中', content: '各智能体正在协商最优方案...' },
                { delay: 180000, title: '🔄 方案优化中', content: '正在优化旅行计划...' },
                { delay: 240000, title: '⏳ 即将完成', content: '正在整合最终结果，请稍候...' }
            ];
            
            progressSteps.forEach(step => {
                const timerId = setTimeout(() => {
                    if (!negotiationEnded && submitBtn.disabled) {
                        addNegotiationStep({
                            type: 'thinking',
                            title: step.title,
                            content: step.content
                        });
                    }
                }, step.delay);
                activeTimers.push(timerId);
            });

            // 发送WebSocket消息
            if (websocket && isConnected) {
                websocket.send(JSON.stringify({
                    type: 'start_negotiation',
                    message: userMessage,
                    details: {
                        destination,
                        duration,
                        budget,
                        preferences,
                        constraints
                    }
                }));
            } else {
                // 如果WebSocket未连接，直接发送HTTP请求
                sendNegotiationRequest(userMessage);
            }
        }

        // 发送协商请求并展示实时过程
        async function sendNegotiationRequest(message) {
            try {
                // 首先显示协商步骤的开始
                showNegotiationStart(message);
                
                // 设置5分钟超时（复杂多Agent协商需要更长时间）
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 300000);
                
                const response = await fetch('http://localhost:8000/api/chat?t=' + Date.now(), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Cache-Control': 'no-cache'
                    },
                    body: JSON.stringify({
                        message: message,
                        user_id: 'web_user_' + Date.now()
                    }),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);

                const result = await response.json();

                if (response.ok) {
                    // 显示协商过程步骤
                    showNegotiationProcess(result);
                    
                    // 显示最终结果
                    showFinalResult(result.response);
                    updateProgress(100);
                    submitBtn.disabled = false;
                    submitBtn.textContent = '🚀 开始AI团队协商';
                    negotiationEnded = true;
                    clearAllTimers();
                } else {
                    showError(result.detail || '请求失败');
                }

            } catch (error) {
                console.error('请求失败:', error);
                if (error.name === 'AbortError') {
                    addNegotiationStep({
                        type: 'error',
                        title: '⏰ 处理时间较长',
                        content: '高预算旅行规划需要复杂的多智能体协商，通常需要2-5分钟。\n\n💡 建议：\n• 尝试更具体的需求（如明确目的地和天数）\n• 或测试低预算查询（响应更快）\n• 系统可能仍在后台处理，请稍后重试'
                    });
                } else {
                    showError('网络请求失败: ' + error.message);
                }
                submitBtn.disabled = false;
                submitBtn.textContent = '🚀 开始AI团队协商';
            }
        }

        // 显示协商开始
        function showNegotiationStart(message) {
            addNegotiationStep({
                type: 'thinking',
                title: '🚀 系统启动中',
                content: '正在连接AI智能体团队，请稍候...'
            });
            
            setTimeout(() => {
                addNegotiationStep({
                    type: 'thinking', 
                    title: '🧠 CoordinatorAgent分析中',
                    content: '正在分析您的旅行需求...'
                });
            }, 1000);
        }

        // 显示协商过程
        function showNegotiationProcess(result) {
            // 解析agents_used来展示协商过程
            const agentsUsed = result.agents_used || [];
            const processingTime = result.processing_time || 0;
            
            // 显示Agent调用过程
            if (agentsUsed.includes('coordinator')) {
                addNegotiationStep({
                    type: 'agreement',
                    title: '🎯 CoordinatorAgent协调完成',
                    content: '已成功协调多个专业Agent进行协作分析'
                });
            }
            
            // 模拟展示预算分析过程
            if (result.response.includes('预算分析')) {
                setTimeout(() => {
                    addNegotiationStep({
                        type: 'thinking',
                        title: '💰 BudgetAgent分析中',
                        content: '正在进行详细的预算分析和优化建议...'
                    });
                }, 500);
                
                setTimeout(() => {
                    addNegotiationStep({
                        type: 'agreement',
                        title: '💰 BudgetAgent分析完成',
                        content: '预算分析已完成，包含详细分配方案和优化建议'
                    });
                }, 1500);
            }
            
            // 显示处理时间
            setTimeout(() => {
                addNegotiationStep({
                    type: 'agreement',
                    title: '⚡ 协商性能统计',
                    content: `总处理时间：${processingTime.toFixed(2)}秒\n参与Agent：${agentsUsed.length}个\n协商轮次：${Math.ceil(processingTime/3)}次`
                });
            }, 2000);
        }

        // 模拟协商过程（演示用）
        function simulateNegotiationProcess(userMessage) {
            const steps = [
                {
                    type: 'thinking',
                    agent: 'CoordinatorAgent',
                    title: '📋 需求分析',
                    content: '正在分析用户旅行需求和偏好...',
                    delay: 1000
                },
                {
                    type: 'dialogue',
                    agent: 'CoordinatorAgent',
                    message: '用户要去汉堡旅行3天，预算800欧元，喜欢户外摄影和历史景点，对天气敏感。',
                    delay: 2000
                },
                {
                    type: 'thinking',
                    agent: 'WeatherAgent',
                    title: '🌤️ 天气数据获取',
                    content: '正在获取汉堡未来3天的天气预报...',
                    delay: 3000
                },
                {
                    type: 'dialogue',
                    agent: 'WeatherAgent',
                    message: '汉堡天气预报：明天多云，12°C；后天雨天，6°C；大后天晴天，18°C。雨天对户外摄影影响很大。',
                    delay: 4000
                },
                {
                    type: 'conflict',
                    title: '⚠️ 冲突检测',
                    content: '发现预算 vs 天气的冲突：雨天需要额外200欧元应对交通和室内活动，但预算只有800欧元。',
                    delay: 5000
                },
                {
                    type: 'thinking',
                    agent: 'BudgetAgent',
                    title: '💰 预算分析',
                    content: '正在分析预算分配和成本优化方案...',
                    delay: 6000
                },
                {
                    type: 'decision',
                    title: '🤝 协商方案',
                    options: [
                        '调整旅行日期到天气更好的时间（+15%住宿成本，-50%天气应对成本）',
                        '重点安排室内活动（-30%摄影体验，节省交通成本）',
                        '混合方案：部分调整日期 + 室内外平衡'
                    ],
                    delay: 7000
                },
                {
                    type: 'agreement',
                    title: '✅ 协商达成',
                    content: '选择混合方案：调整部分日期到天气更好的时间，预算控制在850欧元以内，70%室内活动，30%灵活户外活动。',
                    delay: 8000
                }
            ];

            steps.forEach((step, index) => {
                const timerId = setTimeout(() => {
                    // 若会话已结束或ID不匹配则忽略
                    if (negotiationEnded) return;
                    addNegotiationStep({...step, sessionId: negotiationId});
                    updateProgress((index + 1) / steps.length * 100);
                }, step.delay);
                activeTimers.push(timerId);
            });

            // 完成协商
            const doneTimer = setTimeout(() => {
                if (negotiationEnded) return;
                submitBtn.disabled = false;
                submitBtn.textContent = '🚀 开始AI团队协商';
                updateProgress(100);
                negotiationEnded = true;
                clearAllTimers();
            }, 9000);
            activeTimers.push(doneTimer);
        }

        // 添加协商步骤
        function addNegotiationStep(step) {
            const stepDiv = document.createElement('div');
            stepDiv.className = `negotiation-step ${step.type || ''}`;

            const stepIcon = getStepIcon(step.type);
            const currentTime = new Date().toLocaleTimeString();

            stepDiv.innerHTML = `
                <div class="step-header">
                    <div class="step-icon" style="background: ${getStepColor(step.type)}">${stepIcon}</div>
                    <div class="step-title">${step.title}</div>
                    <div class="step-time">${currentTime}</div>
                </div>
                <div class="step-content">${step.content || ''}</div>
            `;

            negotiationPanel.appendChild(stepDiv);
            negotiationPanel.scrollTop = negotiationPanel.scrollHeight;

            currentStep++;
        }

        function clearAllTimers() {
            activeTimers.forEach(id => clearTimeout(id));
            activeTimers = [];
        }

        // 显示思考过程
        function showThinking(agent, message) {
            const thinkingDiv = document.createElement('div');
            thinkingDiv.className = 'negotiation-step thinking';

            thinkingDiv.innerHTML = `
                <div class="step-header">
                    <div class="thinking-animation"></div>
                    <div class="step-title">${agent} 正在思考...</div>
                    <div class="step-time">${new Date().toLocaleTimeString()}</div>
                </div>
                <div class="step-content">${message}</div>
            `;

            negotiationPanel.appendChild(thinkingDiv);
            negotiationPanel.scrollTop = negotiationPanel.scrollHeight;
        }

        // 添加Agent对话
        function addAgentDialogue(agent, message) {
            const dialogueDiv = document.createElement('div');
            dialogueDiv.className = 'agent-dialogue';

            dialogueDiv.innerHTML = `
                <div class="agent-name">${agent}:</div>
                <div class="agent-message">${message}</div>
            `;

            // 找到最后一个协商步骤，添加到其中
            const lastStep = negotiationPanel.lastElementChild;
            if (lastStep && lastStep.classList.contains('negotiation-step')) {
                lastStep.appendChild(dialogueDiv);
            } else {
                // 如果没有步骤，直接添加到面板
                negotiationPanel.appendChild(dialogueDiv);
            }

            negotiationPanel.scrollTop = negotiationPanel.scrollHeight;
        }

        // 显示决策选项
        function showDecisionOptions(options) {
            const optionsDiv = document.createElement('div');
            optionsDiv.className = 'decision-options';

            optionsDiv.innerHTML = '<strong>请选择协商方案：</strong>';

            options.forEach((option, index) => {
                const optionDiv = document.createElement('div');
                optionDiv.className = 'option';
                optionDiv.textContent = option;
                optionDiv.onclick = () => selectOption(optionDiv, index);
                optionsDiv.appendChild(optionDiv);
            });

            // 找到最后一个协商步骤，添加到其中
            const lastStep = negotiationPanel.lastElementChild;
            if (lastStep && lastStep.classList.contains('negotiation-step')) {
                lastStep.appendChild(optionsDiv);
            }

            negotiationPanel.scrollTop = negotiationPanel.scrollHeight;
        }

        // 选择选项
        function selectOption(optionDiv, index) {
            // 移除其他选项的选中状态
            const options = optionDiv.parentElement.querySelectorAll('.option');
            options.forEach(opt => opt.classList.remove('selected'));

            // 选中当前选项
            optionDiv.classList.add('selected');

            // 模拟选择结果
            setTimeout(() => {
                addNegotiationStep({
                    type: 'agreement',
                    title: '✅ 方案已选择',
                    content: `您选择了：${optionDiv.textContent}`
                });
            }, 1000);
        }

        // 显示最终结果
        function showFinalResult(result) {
            addNegotiationStep({
                type: 'agreement',
                title: '🎉 协商完成',
                content: result
            });
        }

        // 显示错误
        function showError(message) {
            addNegotiationStep({
                type: 'error',
                title: '❌ 协商出错',
                content: message
            });
        }

        // 更新进度
        function updateProgress(progress) {
            progressFill.style.width = `${progress}%`;
            progressText.textContent = `${Math.round(progress)}%`;
        }

        // 基于步骤数量的平滑自增进度（无后端progress时使用）
        let internalProgress = 0;
        function incrementProgress() {
            if (internalProgress < 90) { // 留出尾部空间
                internalProgress += 8; // 每步增加8%
                updateProgress(Math.min(internalProgress, 90));
            }
        }

        // 获取步骤图标
        function getStepIcon(type) {
            const icons = {
                'thinking': '🧠',
                'dialogue': '💬',
                'conflict': '⚠️',
                'decision': '🤝',
                'agreement': '✅',
                'error': '❌'
            };
            return icons[type] || '📝';
        }

        // 获取步骤颜色
        function getStepColor(type) {
            const colors = {
                'thinking': '#ff9800',
                'dialogue': '#2196f3',
                'conflict': '#f44336',
                'decision': '#9c27b0',
                'agreement': '#4caf50',
                'error': '#f44336'
            };
            return colors[type] || '#4facfe';
        }

        // 检查Agent状态
        async function checkAgentsStatus() {
            try {
                const response = await fetch('http://localhost:8000/api/agents/status');
                const agents = await response.json();

                // 更新状态指示器
                updateAgentStatus('weatherStatus', agents.weather?.status === '在线');
                updateAgentStatus('budgetStatus', agents.budget?.status === '在线');
                updateAgentStatus('travelStatus', agents.travel?.status === '在线');
                updateAgentStatus('restaurantStatus', agents.restaurant?.status === '在线');
                updateAgentStatus('coordinatorStatus', agents.coordinator?.status === '在线');

            } catch (error) {
                console.error('检查Agent状态失败:', error);
                updateAgentStatus('weatherStatus', false);
                updateAgentStatus('budgetStatus', false);
                updateAgentStatus('travelStatus', false);
                updateAgentStatus('restaurantStatus', false);
                updateAgentStatus('coordinatorStatus', false);
            }
        }

        // 添加数据流条目
        function addDataFlowEntry(data) {
            const flowDiv = document.createElement('div');
            flowDiv.className = `agent-flow ${data.type || ''}`;

            const agentIcon = getAgentIcon(data.agent);
            const agentColor = getAgentColor(data.agent);

            flowDiv.innerHTML = `
                <div class="agent-header">
                    <div class="agent-icon" style="background: ${agentColor}">${agentIcon}</div>
                    <div class="agent-info">
                        <h3>${data.agent || 'Unknown Agent'}</h3>
                        <p>${data.description || 'Agent协作步骤'}</p>
                    </div>
                </div>
                
                ${data.input ? `
                <div class="data-section">
                    <h4>📥 输入数据</h4>
                    <div class="data-content">${formatData(data.input)}</div>
                </div>
                ` : ''}
                
                ${data.output ? `
                <div class="data-section">
                    <h4>📤 输出数据</h4>
                    <div class="data-content">${formatData(data.output)}</div>
                </div>
                ` : ''}
                
                ${data.upstream || data.downstream ? `
                <div class="data-section">
                    <h4>🔗 数据流关系</h4>
                    <div class="data-content">
                        ${data.upstream ? `上游: ${data.upstream}<br>` : ''}
                        ${data.downstream ? `下游: ${data.downstream}` : ''}
                    </div>
                </div>
                ` : ''}
            `;

            dataFlowPanel.appendChild(flowDiv);
            dataFlowPanel.scrollTop = dataFlowPanel.scrollHeight;
        }

        // 格式化数据显示
        function formatData(data) {
            if (typeof data === 'string') {
                return data;
            }
            return JSON.stringify(data, null, 2);
        }

        // 获取Agent图标
        function getAgentIcon(agent) {
            const icons = {
                'CoordinatorAgent': '🎯',
                'IntelligentWeatherAgent': '🌤️',
                'BudgetAgent': '💰',
                'TravelAgent': '🗺️',
                'RestaurantAgent': '🍽️'
            };
            return icons[agent] || '🤖';
        }

        // 获取Agent颜色
        function getAgentColor(agent) {
            const colors = {
                'CoordinatorAgent': '#2196f3',
                'IntelligentWeatherAgent': '#4caf50',
                'BudgetAgent': '#ff9800',
                'TravelAgent': '#9c27b0',
                'RestaurantAgent': '#f44336'
            };
            return colors[agent] || '#666';
        }
    </script>
</body>
</html>
